﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using Newtonsoft.Json;
using System.Collections;
using Systen.Shop.Members.Models;
using DaiMaoSource.ShopMember.ViewModels.MemberVMs;
using Systen.Core.DTO;
using Systen.Shop.Orders.Models;
using Systen.Shop.Orders.Enum;
using DaiMaoSource.ShopOrder.ViewModels.OtoOrderVMs;
using Systen.Shop.Products.Models;
using Systen.Shop.Core.Models;
using WalkingTec.Mvvm.Core.Support.Json;
using DaiMaoSource.Helpers;
using Systen.Shop.Artificer.Models;
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using WxPayAPI;
using Systen.Wechat.Pay.Models;
using Systen.Wechat.Pay.Enums;
using System.IO;
using System.Security.Cryptography.X509Certificates;

namespace DaiMaoSource.Controllers
{
    [ActionDescription("")]
    [ApiController]
    [Route("api/v1/Wechat")]
    public partial class OtoOrderApiController : ApiMemberBaseController
    {

        [HttpGet]
        public OperationResult ToOrderQuery(string orderId, string tid)
        {
            var result = new OperationResult()
            {
                StatusCode = OperationResultStatus.Success,
            };
            result.Message = WxPayAPI.OrderQuery.Run(tid, orderId);
            return result;
        }

        /// <summary>
        /// app 统一下单 预支付Id获取
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="tradeType">支付类型
        /// JSAPI -JSAPI支付 公众号
        /// NATIVE -Native支付
        /// H5支付的交易类型为MWEB
        /// APP -APP支付</param>
        /// <returns></returns>
        [HttpGet("GetUnifiedorder")]
        public OperationResult GetUnifiedorder(string orderId, string openId = "", string tradeType = "JSAPI")
        {
            Log.Debug(this.GetType().ToString(), "统一下单");
            var result = new OperationResult()
            {
                StatusCode = OperationResultStatus.Error,
                Message = "获取预支付信息失败",
            };

            //return result;

            #region openid是否读取登录账号的openid？（待确认）
            if (LoginMemberInfo == null)
            {
                result.StatusCode = OperationResultStatus.LoginTimeout;
                result.Message = "身份验证失败或超时";
                return result;
            }
            openId = LoginMemberInfo.OpenId;
            #endregion

            var orderInfo = DC.Set<OtoOrder>()
                .CheckEqual(true, x => x.IsValid)
                .CheckEqual(orderId, x => x.OrderId).FirstOrDefault();
            if (orderInfo == null)
            {
                Log.Error(this.GetType().ToString(), "没有此订单号 : " + orderId);
                result.Message = "没有此订单号!";
                return result;
            }
            if (orderInfo.OrderStatus != OrderStatuss.WaitPay)
            {
                Log.Error(this.GetType().ToString(), "订单状态错误 : " + orderInfo.OrderStatus);
                result.Message = "只有待支付状态申请支付";
                return result;
            }

            #region 暂时不适用
            ////是否登录
            //Member loginMember = LoginMemberInfo;
            //if (loginMember == null)
            //{
            //    result.StatusCode = OperationResultStatus.LoginTimeout;
            //    result.Message = "身份验证失败或超时";
            //    return result;
            //}
            ////优惠券是否已使用
            //if (orderInfo.CouponId != 0)
            //{
            //    DateTime dt = DateTime.Now;
            //    IList<ICriterion> criterionList = new List<ICriterion>();
            //    criterionList.Add(Restrictions.Eq(Systen.Cms.Coupon.Domain.MemberCoupon.ColumnNames.Id, orderInfo.CouponId));
            //    Systen.Cms.Coupon.Domain.MemberCoupon memberCouponInfo = MemberCouponService.Get(criterionList.ToArray());
            //    if (memberCouponInfo != null)
            //    {
            //        if (memberCouponInfo.IsValid == false)
            //        {
            //            result.Message = "优惠券已失效，请重新下单";
            //            return result;
            //        }
            //        if (memberCouponInfo.IsUsed)
            //        {
            //            result.Message = "优惠券已使用，请重新下单";
            //            return result;
            //        }
            //        if (memberCouponInfo.EffectiveStartTime > dt)
            //        {
            //            result.Message = "优惠券未到使用日期，请重新下单";
            //            return result;
            //        }
            //        if (memberCouponInfo.EffectiveEndTime < dt)
            //        {
            //            result.Message = "优惠券未到使用日期，请重新下单";
            //            return result;
            //        }
            //    }
            //    else
            //    {
            //        result.Message = "优惠券不存在，请重新下单";
            //        return result;
            //    }
            //}
            #endregion

            WxPayData wxPayData = new WxPayData();
            wxPayData.SetValue("out_trade_no", orderId.ToString());
            Log.Debug(this.GetType().ToString(), "out_trade_no值 : " + wxPayData.GetValue("out_trade_no"));

            //商品描述交易字段格式根据不同的应用场景按照以下格式：
            // APP——需传入应用市场上的APP名字 - 实际商品名称，天天爱消除 - 游戏充值。
            wxPayData.SetValue("description", orderInfo.OrderName);
            Log.Debug(this.GetType().ToString(), "description值 : " + wxPayData.GetValue("description"));
            //订单总金额，单位为分
            wxPayData.SetValue("total", Convert.ToInt32(orderInfo.ProductTotalAmount * 100));
            Log.Debug(this.GetType().ToString(), "total值 : " + wxPayData.GetValue("total"));
            //JSAPI时（即JSAPI支付），openid 此参数必传
            if (tradeType == "JSAPI")
            {
                if (string.IsNullOrEmpty(openId))
                {
                    result.Message = "微信未授权";
                    return result;
                }
                wxPayData.SetValue("openid", openId);
                Log.Debug(this.GetType().ToString(), "openid值 : " + wxPayData.GetValue("openid"));
            }

            var resultWxPayData = WxPayApi.UnifiedOrder(wxPayData);
            var prepay_id = resultWxPayData.GetValue("prepay_id").ToString();
            Log.Debug(this.GetType().ToString(), "prepay_id值 : " + resultWxPayData.GetValue("prepay_id"));
            if (string.IsNullOrEmpty(prepay_id))
            {
                Log.Error(this.GetType().ToString(), "prepay_id值错误 : ");
                result.Message = "prepay_id错误";
                return result;
            }
            string nonceStr = GetRandomDom(32);//随机字符串
            long timeStamp = ConvertDateTimeToInt(DateTime.Now); //时间戳
            string signType = "RSA";
            string sign = WxPayConfig.APPID + "\n" + timeStamp.ToString() + "\n" + nonceStr + "\n" + "prepay_id=" + prepay_id + "\n";
            var paySign = RSAEncrypt(sign);
            result.Result = new
            {
                timeStamp = timeStamp,
                nonceStr = nonceStr,
                package = prepay_id,
                signType = signType,
                paySign = paySign,
            };

            #region 小程序支付不用，暂时废弃（待整理）
            //if (!string.IsNullOrEmpty(return_code))
            //{
            //    var result_code = resultWxPayData.GetValue("result_code").ToString();
            //    if (result_code == "SUCCESS")
            //    {
            //        var prepay_id = resultWxPayData.GetValue("prepay_id");

            //        WxPayData appData = new WxPayData();
            //        if (tradeType == "JSAPI")
            //        {
            //            //统一下单接口返回的prepay_id参数值
            //            appData.SetValue("appId", WxPayConfig.APPID);
            //            appData.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
            //            appData.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
            //            appData.SetValue("package", "prepay_id=" + prepay_id);
            //            appData.SetValue("paySign", appData.MakeSign());
            //        }
            //        else if (tradeType == "APP")
            //        {
            //            appData.SetValue("appid", WxPayConfig.APPID);//公众账号ID
            //            appData.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
            //            appData.SetValue("noncestr", WxPayApi.GenerateNonceStr());//随机字符串
            //            appData.SetValue("prepayid", prepay_id);
            //            appData.SetValue("partnerid", WxPayConfig.MCHID);//商户号
            //            appData.SetValue("package", "Sign=WXPay");
            //            appData.SetValue("sign", appData.MakeSign());
            //        }
            //        else if (tradeType == "NATIVE")
            //        {
            //            appData.SetValue("appid", WxPayConfig.APPID);//公众账号ID
            //            appData.SetValue("mch_id", WxPayConfig.MCHID);//商户号
            //            appData.SetValue("out_trade_no", orderId.ToString());//订单号
            //            appData.SetValue("nonce_str", resultWxPayData.GetValue("nonce_str").ToString());//随机字符串
            //            appData.SetValue("code_url", resultWxPayData.GetValue("code_url").ToString());
            //            appData.SetValue("sign", resultWxPayData.GetValue("sign").ToString());//签名
            //        }
            //        else if (tradeType == "MWEB")
            //        {
            //            //h5 支付地址
            //            appData.SetValue("wxPayUrl", resultWxPayData.GetValue("mweb_url"));
            //        }

            //        result.Result = appData.GetValues();
            //        var wechatPay = DC.Set<WechatPay>().CheckEqual(orderId, x => x.OrderId);
            //        if (wechatPay == null)
            //        {
            //            DC.Set<WechatPay>().Add(new WechatPay()
            //            {
            //                OrderId = orderId,
            //                PayId = "",
            //                PayState = (int)PayState.NotPay,
            //                PayTime = DateTime.Now
            //            });
            //            DC.SaveChanges();
            //        }
            //    }
            //    else
            //    {
            //        result.Message = resultWxPayData.GetValue("err_code_des").ToString();
            //        return result;
            //    }
            //}
            //else
            //{

            //    return result;
            //}
            #endregion

            result.StatusCode = OperationResultStatus.Success;
            result.Message = "操作成功";
            return result;
        }

        /// <summary>
        /// 小程序调起支付
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpGet("RequestPayment")]
        public OperationResult RequestPayment(string orderId)
        {
            Log.Debug(this.GetType().ToString(), "小程序调起支付Api 开始");
            var result = new OperationResult()
            {
                StatusCode = OperationResultStatus.Error,
                Message = "获取预支付信息失败",
            };

            var wechatPayInfo = DC.Set<WechatPay>().CheckEqual(orderId, x => x.OrderId).FirstOrDefault();
            if (wechatPayInfo == null)
            {
                DC.Set<WechatPay>().Add(new WechatPay()
                {
                    OrderId = orderId,
                    PayId = "",
                    PayState = (int)PayState.NotPay,
                    PayTime = DateTime.Now
                });
                DC.SaveChanges();
            }

            result.StatusCode = OperationResultStatus.Success;
            result.Message = "操作成功";
            return result;
        }

        /// <summary>
        /// 获取微信订单返回值
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        [HttpGet("GetOrder")]
        public OperationResult GetOrder(string orderid)
        {
            var result = new OperationResult()
            {
                StatusCode = OperationResultStatus.Error,
                Message = "查询订单信息失败",
            };

            WxPayData req = new WxPayData();
            req.SetValue("out_trade_no", orderid);
            WxPayData res = WxPayApi.OrderQuery(req);
            if (res.GetValue("trade_state").ToString() == "SUCCESS")
            {
                result.StatusCode = OperationResultStatus.Success;
                result.Result = true;
                result.Message = res.ToString();
                return result;
            }

            result.StatusCode = OperationResultStatus.Success;
            result.Result = false;
            result.Message = "no";
            return result;
        }

        //支付回调
        [HttpPost("PaymentCallback")]
        public void PaymentCallback()
        {
            Log.Debug(this.GetType().ToString(), "step_00");
            ResultNotify resultNotify = new ResultNotify(HttpContext);
            // 支付回调验签
            WxPayData notifyData = resultNotify.GetNotifyData();
            Log.Debug(this.GetType().ToString(), "step_01");

            //检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {
                Log.Debug(this.GetType().ToString(), "step_02");
                //若transaction_id不存在，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("code", "FAIL");
                res.SetValue("message", "支付结果中微信订单号不存在");
                Log.Error(this.GetType().ToString(), "支付结果错误 : " + res.ToXml());
                byte[] buffer = null;
                string result = res.ToJson();
                buffer = Encoding.Default.GetBytes(result);
                using (MemoryStream stream = new MemoryStream())
                {
                    stream.Write(buffer);
                    HttpContext.Response.Body = stream;
                }
            }

            Log.Debug(this.GetType().ToString(), "step_03");
            string transaction_id = notifyData.GetValue("out_trade_no").ToString();
            Log.Debug(this.GetType().ToString(), transaction_id);

            //查询订单，判断订单真实性
            WxPayData req = new WxPayData();
            req.SetValue("out_trade_no", transaction_id);
            WxPayData resq = WxPayApi.OrderQuery(req);
            if (resq.GetValue("trade_state").ToString() != "SUCCESS")
            {
                Log.Debug(this.GetType().ToString(), "step_04");
                //若订单查询失败，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("code", "FAIL");
                res.SetValue("message", "订单查询失败");
                Log.Error(this.GetType().ToString(), "订单查询失败 : " + res.ToXml());
                byte[] buffer = null;
                string result = res.ToJson();
                buffer = Encoding.Default.GetBytes(result);
                using (MemoryStream stream = new MemoryStream())
                {
                    stream.Write(buffer);
                    HttpContext.Response.Body = stream;
                }
                //HttpContext.Current.Response.End();
            }
            //查询订单成功
            else
            {
                Log.Debug(this.GetType().ToString(), "step_05");
                WxPayData res = new WxPayData();
                res.SetValue("code", "SUCCESS");
                res.SetValue("message", "成功");
                Log.Debug(this.GetType().ToString(), "order query success : " + res.ToJson());
                // 获取订单信息
                var orderId = notifyData.GetValue("out_trade_no").ToString();
                Log.Debug(this.GetType().ToString(), orderId);
                var orderInfo = DC.Set<OtoOrder>()
                      .CheckEqual(true, x => x.IsValid)
                      .CheckEqual(orderId, x => x.OrderId).FirstOrDefault();
                try
                {
                    Log.Debug(this.GetType().ToString(), "step_06");

                    DateTime dtNow = DateTime.Now;
                    var wechatPay = DC.Set<WechatPay>().CheckEqual(orderInfo.OrderId, x => x.OrderId).FirstOrDefault();
                    if (wechatPay == null)
                    {
                        Log.Debug(this.GetType().ToString(), "wechatPay为Null");
                    }
                    //修改支付记录
                    wechatPay.PayId = transaction_id;//微信订单号
                    wechatPay.PayState = (int)PayState.Payed;
                    wechatPay.PayTime = dtNow;
                    Log.Debug(this.GetType().ToString(), "step_07");

                    #region 暂时不适用
                    ////会员使用优惠卷 更新使用状态
                    //if (orderInfo.CouponId > 0)
                    //{
                    //    DateTime currentDateTime = dtNow;
                    //    IList<ICriterion> criterionList = new List<ICriterion>();
                    //    criterionList.Add(Restrictions.Eq(Systen.Cms.Coupon.Domain.MemberCoupon.ColumnNames.Id, orderInfo.CouponId));
                    //    criterionList.Add(Restrictions.Eq(Systen.Cms.Coupon.Domain.MemberCoupon.ColumnNames.MemberId, memberInfo.Id));
                    //    criterionList.Add(Restrictions.Eq(Systen.Cms.Coupon.Domain.MemberCoupon.ColumnNames.IsValid, true));
                    //    criterionList.Add(Restrictions.Eq(Systen.Cms.Coupon.Domain.MemberCoupon.ColumnNames.IsUsed, false));

                    //    Systen.Cms.Coupon.Domain.MemberCoupon memberCouponInfo = MemberCouponService.Get(criterionList.ToArray());
                    //    if (memberCouponInfo != null)
                    //    {
                    //        memberCouponInfo.IsUsed = true;
                    //        memberCouponInfo.UseTime = dtNow;
                    //        //更新使用优惠券
                    //        MemberCouponService.Update(memberCouponInfo);
                    //    }
                    //}
                    #endregion

                    //修改订单信息（已支付状态）
                    orderInfo.OrderStatus = OrderStatuss.Finish;
                    orderInfo.PaymentTypeName = "Wechat JSAPI";
                    orderInfo.GatewayOrderId = transaction_id;
                    orderInfo.PayDate = dtNow;
                    orderInfo.UpdateTime = dtNow;
                    orderInfo.UpdateBy = "System";
                    orderInfo.FinishDate = dtNow;

                    Log.Debug(this.GetType().ToString(), "step_08");
                    using var transaction = DC.BeginTransaction();
                    try
                    {
                        DC.Set<WechatPay>().Update(wechatPay);
                        DC.Set<OtoOrder>().Update(orderInfo);
                        //添加订单修改记录
                        AddOrderOperationLogs(orderInfo.ID, "微信支付回调修改");
                        DC.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                    }

                    byte[] buffer = null;
                    string result = res.ToJson();
                    buffer = Encoding.Default.GetBytes(result);
                    using (MemoryStream stream = new MemoryStream())
                    {
                        stream.Write(buffer);
                        HttpContext.Response.Body = stream;
                    }
                }
                catch (Exception e)
                {
                    Log.Debug(this.GetType().ToString(), e.Message);
                    throw;
                }


                //HttpContext.Response.Body(res.ToXml());
                //HttpContext.Current.Response.End();
            }
        }

        /// <summary>
        /// 生成不重复随机字符串
        /// </summary>
        /// <param name="count">输入字符串长度</param>
        /// <returns>字符串</returns>
        private static string GetRandomDom(int count)
        {
            string t62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

            long ticks = DateTime.Now.Ticks;

            string gen = "";
            int ind = 0;
            while (ind < count)
            {
                byte low = (byte)((ticks >> ind * 6) & 61);
                gen += t62[low];
                ind++;
            }
            return gen;
        }

        /// <summary>  
        /// 将c# DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time">时间</param>  
        /// <returns>long</returns>  
        public static long ConvertDateTimeToInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
            return t;
        }

        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="publickey"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RSAEncrypt(string content)
        {
            string privateKey = $"{WxPayConfig._Privatekey}";
            byte[] keyData = Convert.FromBase64String(privateKey);
            var rsa = RSA.Create();
            rsa.ImportPkcs8PrivateKey(keyData, out _);
            byte[] data = System.Text.Encoding.UTF8.GetBytes(content);
            return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
        }

        /// <summary> 
        /// 获取签名证书私钥 
        /// </summary> 
        /// <param name="priKeyFile"></param> 
        /// <param name="keyPwd"></param> 
        /// <returns></returns> 
        private static RSA GetPrivateKey(string priKeyFile, string keyPwd)
        {
            X509Certificate2 cert = new X509Certificate2(priKeyFile, keyPwd);
            return cert.GetRSAPrivateKey();
        }

        /// <summary>
        /// 添加订单日志记录
        /// </summary>
        /// <param name="OtoOrderInfoId"></param>
        /// <param name="OperateContent"></param>
        private void AddOrderOperationLogs(Guid OtoOrderInfoId, string OperateContent)
        {
            //获取操作人类型
            int operatorUserType = 80;
            string operatorUserTypeName = "微信支付回调";
            DateTime dateTime = DateTime.Now;
            //记录订单操作记录
            OrderOperationLogs orderOperationLogs = new OrderOperationLogs()
            {
                OtoOrderInfoId = OtoOrderInfoId,  //订单ID
                OperatorUserId = new Guid(),  //操作人Id
                UserAccount = "Wechat",  //操作人账号
                NickName = "Wechat",  //操作人昵称
                OperateContent = OperateContent,  //操作内容
                OperatorUserType = operatorUserType,  //操作人类型
                OperatorUserTypeName = operatorUserTypeName,  //操作人类型名称
                OperateDate = dateTime,  //操作日期
                CreateBy = "Wechat",
                CreateTime = dateTime,
            };
            DC.Set<OrderOperationLogs>().Add(orderOperationLogs);
        }

        ////用户直接申请退款
        //[HttpGet]
        ////[MemberAuthorize]
        //public OperationResult UserRefund(long orderId)
        //{
        //    var result = new OperationResult()
        //    {
        //        StatusCode = OperationResultStatus.Error,
        //        Message = "订单号不存在!"
        //    };
        //    //是否登录
        //    Member loginMember = LoginMemberInfo;
        //    if (loginMember == null || loginMember.Id < 1)
        //    {
        //        result.StatusCode = OperationResultStatus.LoginTimeout;
        //        result.Message = "登录超时";
        //        return result;
        //    }
        //    //匹配订单号是否 属于登录人
        //    var orderInfo = OrderService.Get(Restrictions.Eq(OtoOrder.ColumnNames.Id, orderId));
        //    if (orderInfo == null)
        //    {
        //        return result;
        //    }
        //    else if (orderInfo.OrderStatus != Convert.ToInt32(OrderStatus.Finished))
        //    {
        //        result.Result = orderInfo;
        //        result.Message = "订单非已支付状态";
        //        return result;
        //    }
        //    else if (orderInfo.PaymentType != 20)
        //    {
        //        result.Result = orderInfo;
        //        result.Message = "非微信支付";
        //        return result;
        //    }

        //    //添加退货申请
        //    OtoReturnApply orderRefund = new OtoReturnApply();
        //    orderRefund.OtoOrderId = orderInfo.Id;
        //    orderRefund.ApplyType = 0;
        //    orderRefund.ApplyTime = DateTime.Now;
        //    orderRefund.ApplyMenberId = loginMember.Id;
        //    orderRefund.ApplyMenberName = loginMember.UserName;
        //    orderRefund.ProblemDescription = "退还押金";
        //    orderRefund.ReplyUserId = 1;
        //    orderRefund.ReplyUserName = "微信";
        //    orderRefund.ReplyTime = DateTime.Now;
        //    orderRefund.Status = 0;
        //    OtoReturnApplyService.Add(orderRefund);

        //    WxPayData wxPayData = new WxPayData();
        //    wxPayData.SetValue("out_trade_no", orderId.ToString());
        //    //t商户退款单号
        //    wxPayData.SetValue("out_refund_no", orderRefund.Id.ToString());
        //    //订单总金额，单位为分，只能为整数，
        //    wxPayData.SetValue("total_fee", Convert.ToInt32((orderInfo.OrderTotalAmount)));
        //    //退款总金额，订单总金额，单位为分，只能为整数
        //    wxPayData.SetValue("refund_fee", Convert.ToInt32(orderInfo.RefundTotalAmount));
        //    //wxPayData.SetValue("refund_fee", 1);
        //    wxPayData.SetValue("notify_url", WxPayConfig.NOTIFY_RETRUN_URL);
        //    wxPayData.SetValue("op_user_id", loginMember.Id.ToString());

        //    var resultWxPayData = WxPayApi.Refund(wxPayData);
        //    var return_code = resultWxPayData.GetValue("return_code").ToString();
        //    if (return_code == "SUCCESS")
        //    {
        //        var result_code = resultWxPayData.GetValue("result_code").ToString();
        //        if (result_code == "SUCCESS")
        //        {
        //            //添加操作日志
        //            OrderOperationLogsService.Add(new OtoOrderLog()
        //            {
        //                OperationTime = DateTime.Now,
        //                OperationUserId = orderInfo.MenberId,
        //                OperationUserName = orderInfo.MenberName,
        //                OperationType = 90,
        //                Remarks = "(微信反馈)订单退款提交申请",
        //                OtoOrderId = orderId,
        //                OrderStatus = (int)OrderStatus.RefundSuccess,
        //            });
        //            result.StatusCode = OperationResultStatus.Success;
        //            result.Message = "操作成功！";
        //            Log.Info("WechatPayRefundApi", "退款成功提交");
        //        }
        //        else
        //        {
        //            result.StatusCode = OperationResultStatus.Error;
        //            result.Message = "操作失败！";
        //        }
        //    }
        //    else
        //    {
        //        result.StatusCode = OperationResultStatus.Error;
        //        result.Message = "操作失败！";
        //    }

        //    return result;
        //}

        ////退款返回结果
        //[AllowAnonymous]
        //public void ResultOrder()
        //{
        //    Log.Error("WechatPayRefundApi", "退款返回结果");
        //    RefundNotify resultNotify = new RefundNotify(HttpContext);

        //    WxPayData notifyData = resultNotify.GetNotifyData();
        //    if (!notifyData.IsSet("return_code") || notifyData.GetValue("return_code").ToString() != "SUCCESS" || !notifyData.IsSet("req_info"))
        //    {
        //        WxPayData res = new WxPayData();
        //        res.SetValue("return_code", "FAIL");
        //        res.SetValue("return_msg", "未返回正确微信支付退款解密信息");
        //        Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml());
        //        Log.Error("WechatPayRefundApi", "未返回正确微信支付退款解密信息");
        //        HttpContext.Current.Response.Write(res.ToXml());
        //        HttpContext.Current.Response.End();
        //    }
        //    //信息解密
        //    string reqInfo = RefundNotify.DecodeReqInfo(notifyData.GetValue("req_info").ToString());
        //    if (reqInfo == null)
        //    {
        //        WxPayData res = new WxPayData();
        //        res.SetValue("return_code", "FAIL");
        //        res.SetValue("return_msg", "解密信息出错");
        //        Log.Error("WechatPayRefundApi", "解密信息出错");
        //        HttpContext.Current.Response.Charset = "utf-8";
        //        HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
        //        HttpContext.Current.Response.Write(res.ToXml());
        //        HttpContext.Current.Response.End();
        //    }
        //    else
        //    {
        //        WxPayData data = new WxPayData();
        //        data.FromXmlNoCheckSign(reqInfo);

        //        //修改订单  完成退款
        //        long orderId = Convert.ToInt64(data.GetValue("out_trade_no"));
        //        var orderInfo = OrderService.Get(orderId);
        //        Log.Error("WechatPayRefundApi", "退款完成操作日志");
        //        //添加操作日志
        //        OrderOperationLogsService.Add(new OtoOrderLog()
        //        {
        //            OperationTime = DateTime.Now,
        //            OperationUserId = orderInfo.MenberId,
        //            OperationUserName = orderInfo.MenberName,
        //            OperationType = 90,
        //            Remarks = "(微信反馈)订单退款成功",
        //            OtoOrderId = orderId,
        //            OrderStatus = (int)OrderStatus.RefundSuccess,
        //        });

        //        WxPayData res = new WxPayData();
        //        res.SetValue("return_code", "SUCCESS");
        //        res.SetValue("return_msg", "OK");

        //        HttpContext.Current.Response.Charset = "utf-8";
        //        HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
        //        HttpContext.Current.Response.Write(res.ToXml());
        //        HttpContext.Current.Response.End();
        //    }
        //}
    }
}
